package com.hk.core.authentication.api.menus;

import com.hk.commons.util.CollectionUtils;
import com.hk.commons.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author Kevin
 */
public interface MenuManager {

    /**
     * 获取当前用户菜单
     */
    List<Menu> getCurrentUserMenu();

    /**
     * 判断菜单是否有角色或权限
     */
    static boolean hasRoleOrPermission(Menu menu, Set<String> roleNames, Set<String> permNames) {
        var roles = menu.getRoles();
        var perms = menu.getPerms();
        return (CollectionUtils.isNotEmpty(roles) &&
                CollectionUtils.isNotEmpty(roleNames) &&
                CollectionUtils.containsAny(roles.stream().map(Menu.Role::getValue)
                        .collect(Collectors.toSet()), roleNames.toArray(new String[0]))) ||
                (CollectionUtils.isNotEmpty(perms) &&
                        CollectionUtils.isNotEmpty(permNames) &&
                        CollectionUtils.containsAny(perms.stream().map(Menu.Perm::getValue)
                                .collect(Collectors.toSet()), permNames.toArray(new String[0])));

    }

    static List<Menu> filterRolesAndPerms(List<Menu> menuList, Set<String> roles, Set<String> perms) {
        return menuList.stream().filter(item -> {
            if (CollectionUtils.isNotEmpty(item.getChildren())) {
                item.setChildren(filterRolesAndPerms(item.getChildren(), roles, perms));
                if (!item.getChildren().isEmpty()) {
                    return true; //如果有子级菜单有权限，父级菜单也要有权限
                } else if (StringUtils.isEmpty(item.getComponent())) {
                    return false; //如果所有子级菜单都没有权限，且component值为null(为折叠菜单)，此菜单也不匹配
                }
            }
            return hasRoleOrPermission(item, roles, perms);
        }).toList();
    }
}
